import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getCurrentUser, isAdmin } from '@/middleware/auth';
import { AuthService } from '@/lib/auth';
import { Permission } from '@/lib/db/auth-schema';

/**
 * 获取权限详情
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id } = params;
    const db = await getDb();

    // 获取权限基本信息
    const permissionResult = await db.findOne<Permission>('permissions', { id });
    const permission = permissionResult.success ? permissionResult.data : null;

    if (!permission) {
      return NextResponse.json(
        { success: false, error: '权限不存在' },
        { status: 404 }
      );
    }

    // 获取使用此权限的角色（简化版本）
    const relatedRoles: any[] = [];

    // 获取拥有此权限的用户（简化版本）
    const relatedUsers: any[] = [];

    return NextResponse.json({
      success: true,
      data: {
        permission,
        relatedRoles,
        relatedUsers,
        usage: {
          roleCount: relatedRoles.length,
          userCount: relatedUsers.length
        }
      }
    });

  } catch (error) {
    console.error('获取权限详情失败:', error);
    return NextResponse.json(
      { success: false, error: '获取权限详情失败' },
      { status: 500 }
    );
  }
}

/**
 * 更新权限信息
 */
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id } = params;
    const body = await request.json();
    const { name, display_name, description, category, resource_type, resource_id, action, is_active } = body;

    const db = await getDb();

    // 检查权限是否存在
    const permissionResult = await db.findOne<Permission>('permissions', { id });
    const permission = permissionResult.success ? permissionResult.data : null;

    if (!permission) {
      return NextResponse.json(
        { success: false, error: '权限不存在' },
        { status: 404 }
      );
    }

    // 如果要修改权限名称，检查是否已存在
    if (name && name !== permission.name) {
      const existingResult = await db.findOne<Permission>('permissions', { name });
      if (existingResult.success && existingResult.data && existingResult.data.id !== id) {
        return NextResponse.json(
          { success: false, error: '权限名称已存在' },
          { status: 409 }
        );
      }
    }

    // 构建更新数据
    const updateData: Partial<Permission> = {
      updated_at: new Date().toISOString()
    };
    
    if (name) updateData.name = name;
    if (display_name) updateData.display_name = display_name;
    if (description !== undefined) updateData.description = description;
    if (category) updateData.category = category;
    if (resource_type) updateData.resource_type = resource_type;
    if (resource_id !== undefined) updateData.resource_id = resource_id;
    if (action) updateData.action = action;
    if (is_active !== undefined) updateData.is_active = is_active;

    if (Object.keys(updateData).length === 1) { // 只有updated_at
      return NextResponse.json(
        { success: false, error: '没有提供要更新的字段' },
        { status: 400 }
      );
    }

    // 执行更新
    const updateResult = await db.update<Permission>('permissions', { id }, updateData);

    if (!updateResult.success) {
      return NextResponse.json(
        { success: false, error: '更新权限失败' },
        { status: 500 }
      );
    }

    // 获取更新后的权限信息
    const updatedPermissionResult = await db.findOne<Permission>('permissions', { id });
    const updatedPermission = updatedPermissionResult.success ? updatedPermissionResult.data : null;

    return NextResponse.json({
      success: true,
      data: updatedPermission,
      message: '权限更新成功'
    });

  } catch (error) {
    console.error('更新权限失败:', error);
    return NextResponse.json(
      { success: false, error: '更新权限失败' },
      { status: 500 }
    );
  }
}

/**
 * 删除权限
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { id } = params;
    const db = await getDb();

    // 检查权限是否存在
    const permissionResult = await db.findOne<Permission>('permissions', { id });
    const permission = permissionResult.success ? permissionResult.data : null;

    if (!permission) {
      return NextResponse.json(
        { success: false, error: '权限不存在' },
        { status: 404 }
      );
    }

    // 检查是否为系统权限（不允许删除）
    if (permission.category === 'system') {
      return NextResponse.json(
        { success: false, error: '系统权限不允许删除' },
        { status: 403 }
      );
    }

    // 删除权限
    const deleteResult = await db.delete('permissions', { id });
    
    if (!deleteResult.success) {
      return NextResponse.json(
        { success: false, error: '删除权限失败' },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      message: `权限 ${permission.display_name} 删除成功`
    });

  } catch (error) {
    console.error('删除权限失败:', error);
    return NextResponse.json(
      { success: false, error: '删除权限失败' },
      { status: 500 }
    );
  }
}